package com.buaa.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.buaa.common.Result;
import com.buaa.dto.AccidentSceneMapDTO;
import com.buaa.dto.TrafficIncidentDTO;
import com.buaa.entity.TrafficIncident;
import com.buaa.entity.User;
import com.buaa.enums.ResponseCode;
import com.buaa.exception.ServiceException;
import com.buaa.mapper.TrafficIncidentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class TrafficIncidentServiceImpl extends ServiceImpl<TrafficIncidentMapper, TrafficIncident> implements IService<TrafficIncident> {

    @Autowired
    private TrafficIncidentMapper trafficIncidentMapper;
    @Autowired
    private UserServiceImpl userServiceImpl;
    private long countTotal(){
        return this.count();
    }

    /**
     * 计算当前开放案件的数量。
     * 本方法通过查询交通事件数据来获取当前状态为开放的案件数量。
     * 如果查询过程中发生异常，将抛出一个包含错误代码和描述的服务异常。
     *
     * @return 当前开放案件的数量。
     * @throws ServiceException 如果查询交通事件数据时发生异常。
     */
    public long countOpenCase(){
        // 初始化开放案件数量变量
        long openIncident = 0;
        try {
            //
            openIncident = trafficIncidentMapper.getOpenCase();
        }catch (Exception e) {
            new ServiceException(ResponseCode.COMMON_SYS_ERROR.getKey(), ResponseCode.COMMON_SYS_ERROR.getDesc());
        }
        return openIncident;
    }
    /**
     * 计算已关闭的交通事件数量。
     * 本方法尝试通过查询数据库来获取已关闭的交通事件数量。如果查询过程中发生异常，
     * 则会抛出一个自定义的服务异常，指示系统发生错误。
     *
     * @return 已关闭的交通事件数量。如果查询失败，返回0。
     */
    public long countClosedCase(){
        long closedIncident = 0;
        try {
            closedIncident = trafficIncidentMapper.getClosedCase();
        }catch (Exception e) {
            new ServiceException(ResponseCode.COMMON_SYS_ERROR.getKey(), ResponseCode.COMMON_SYS_ERROR.getDesc());
        }
        return closedIncident;
    }

    public Result updateTrafficIncident(@RequestBody TrafficIncidentDTO dto, HttpServletRequest request) {
        return null;
    }

    public Result deleteByTrafficIncidentId(@PathVariable("id") Integer id, HttpServletRequest request) {
        return null;
    }

    public Result saveTrafficIncident(@RequestBody TrafficIncidentDTO dto, HttpServletRequest request) {
        User currentOpUser = userServiceImpl.getOperateUser(request);
        TrafficIncident sceneMap = new TrafficIncident();
        BeanUtil.copyProperties(dto, sceneMap, true);
        sceneMap.setCreateTime(LocalDateTime.now());
        sceneMap.setCreateBy(currentOpUser.getUserName());
        boolean result = false;
        try {
            result = saveOrUpdate(sceneMap);
        } catch (ServiceException e) {
            new ServiceException(ResponseCode.DB_EXEC_ERROR.getKey(), ResponseCode.DB_EXEC_ERROR.getDesc());
        }

        if (result)
            return Result.success(ResponseCode.POLICE_INCIDENT_SUCCESS.getKey(), ResponseCode.POLICE_INCIDENT_SUCCESS.getDesc(), "");
        else
            return Result.success(ResponseCode.POLICE_INCIDENT_FAILURE.getKey(), ResponseCode.POLICE_INCIDENT_FAILURE.getDesc(), "");
    }
    public Map<String, Object> findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        pageNum = (pageNum - 1) * pageSize;
        // 创建一个分页对象，指定页码和每页大小
        IPage<TrafficIncident> page = new Page<>(pageNum, pageSize);
        QueryWrapper<TrafficIncident> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time")
                .last("LIMIT " + pageNum + "," + pageSize);
        Map<String, Object> res = new HashMap<>();
        try {
            //调用page方法，根据分页对象查询用户信息
            IPage<TrafficIncident> userPage = page(page, queryWrapper); // 调用 page 方法
            List<TrafficIncident> userList = userPage.getRecords();
            List<AccidentSceneMapDTO> dtoList = new ArrayList<AccidentSceneMapDTO>();
            BeanUtil.copyProperties(userList, dtoList, true);

            res.put("pagedata", userList);
            res.put("total", countTotal());
        } catch (ServiceException e) {
            new ServiceException(ResponseCode.DB_EXEC_ERROR.getKey(), ResponseCode.DB_EXEC_ERROR.getDesc());
        }
        return res;
        // 返回查询结果中的用户记录列表
    }

    public List<TrafficIncidentDTO> getIncidentByMonth() {

        List<TrafficIncidentDTO> trafficIncidentDTOS = null;
        try {
            trafficIncidentDTOS = trafficIncidentMapper.getIncidentByMonth();
        }catch (Exception e) {
            new ServiceException(ResponseCode.COMMON_SYS_ERROR.getKey(), ResponseCode.COMMON_SYS_ERROR.getDesc());
        }
        return trafficIncidentDTOS;
    }
}
